from logging import getLogger

from zope import component
from Acquisition import aq_inner
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.memoize import ram, instance
from plone.app.portlets.portlets import base
from plone.memoize.compress import xhtml_compress

from meercat.ui.plone.content.interfaces import IMeercatSearch
from meercat.ui.plone.browser.interfaces import IMeercatSearchView



log = getLogger('meercat.ui.plone.browser.portlets.facetBase')

def render_cachekey(fun, self):
    """
    Generates a key based on:

    * Portal URL
    * Portlet manager
    * Assignment
    * SOLR Query parameters
    
    """
    context = aq_inner(self.context)
    
    return u''.join((
        getToolByName(context, 'portal_url')(),
        self.manager.__name__,
        self.data.__name__,
        self.available and unicode(self.getQueryParameters()) or u'unavailable'))

class BaseFacetRenderer(base.Renderer):
    _template = ViewPageTemplateFile('facets.pt')
    label = None
    
    def __init__(self, *args):
        base.Renderer.__init__(self, *args)
    
    def getTitle(self):
        return self.label
    
    @ram.cache(render_cachekey)
    def render(self):
        log.debug('%s.render()' % (str(self),))
        return xhtml_compress(self._template())
    
    @property
    def available(self):
        log.debug('%s.available()' % (str(self),))
        if not IMeercatSearch.providedBy(self.context):
            return False
        if not IMeercatSearchView.providedBy(self.view):
            return False
        if not self.getQueryParameters():
            return False
        
        return True
    
    def query(self, **params):
        return aq_inner(self.context).getMeercatManager().query(**params)
    
    @instance.memoize
    def getQueryParameters(self):
        params = self.view.getQueryParameters()
        params = self.removeExtraneousParameters(params)
        if params:
            params['facet'] = 'true'
        return params
    
    def getFacetCounts(self):
        params = self.getQueryParameters()
        
        if not params:
            return None
        
        try:
            return self.query(**params).facet_counts
        except AttributeError:
            return None
    
    def removeExtraneousParameters(self, params):
        if not isinstance(params,dict):
            return None
        
        params.pop('sort','')
        params.pop('start','')
        params['rows'] = 0
        
        return params